package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	//"time"
)

type DBworker struct {
	DB *sql.DB
}

//插入数据 insert
func (dbw *DBworker) insertData() {
	stmt, err := dbw.DB.Prepare("INSERT INTO `seckill`.`success_killed`(`seckill_id`, `user_id`, `state`, `create_time`) VALUES (?,?,?,?)")
	if err != nil {
		fmt.Println("Preparefail", err)
		return
	}

	ret, err := stmt.Exec(10001, 2, 1, "2019-09-17 16:55:34")
	if err != nil {
		fmt.Printf("exec insert data error:%v\n", err)
		return
	}
	if LastInsertId, err := ret.LastInsertId(); err == nil {
		fmt.Printf("LastInsertId%d\n", LastInsertId)
	}

	if RowsAffected, err := ret.RowsAffected(); err == nil {
		fmt.Printf("RowsAffected%d\n", RowsAffected)
	}
}

type seckilled struct {
	seckill_id  int64
	user_id     int64
	state       int16
	create_time string
}

//查询数据测试
func (dbw *DBworker) queryData() {

	stmt, _ := dbw.DB.Prepare("select * from success_killed")
	//go defer (go延迟函数) defer语句调用一个函数，这个函数执行会推迟，直到外围的函数返回，或者外围函数运行到最后，或者相应的goroutine panic
	defer stmt.Close()

	rows, err := stmt.Query()
	defer rows.Close()

	if err != nil {
		fmt.Printf("query data error : %v\n", err)
		return
	}
	for rows.Next() {
		var s seckilled
		rows.Scan(&s.seckill_id, &s.user_id, &s.state, &s.create_time)
		fmt.Println(s)
	}

}

//func init() {
//	db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/seckill?charset=utf8")
//	if err != nil {
//		fmt.Println("dbiniterr:", err, db)
//	}
//
//}

func main() {
	db, err := sql.Open("mysql", "root:12345678@tcp(127.0.0.1:3306)/seckill?charset=utf8")
	if err != nil {
		fmt.Println("dbiniterr:", err, db)
	}
	dbw := new(DBworker)
	dbw.DB = db
	dbw.queryData()
}

func checkErr(err error) {
	if err != nil {
		panic(err)
		return
	}
	println("ok")
}
